package cn.kgc.service.impl;

import cn.kgc.commons.util.MD5Util;
import cn.kgc.base.entity.LoginUserInfo;
import cn.kgc.constant.AuthorityCenterConstant;
import cn.kgc.entity.UmsMember;
import cn.kgc.mapper.UmsMemberMapper;
import cn.kgc.service.JwtService;
import cn.kgc.util.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;

/**
 * <p>添加描述信息</p>
 *
 * @author 卢传琪
 * @since 2022年10月17日
 */
@Service(value = "jwtService")
@Slf4j
public class JwtServiceImpl implements JwtService {
    @Resource
    private UmsMemberMapper umsMemberMapper;

    @Override
    public String token(String username, String password) throws Exception {
       return token(username,password, AuthorityCenterConstant.TOKEN_EXPIRE_TIME);
    }

    @Override
    public String token(String username, String password, int expire) throws Exception {
        log.info("name:{},password:{}",username,password);
        //1 判断账号密码是否正确
        LambdaQueryWrapper<UmsMember> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UmsMember::getUsername,username);
        password= MD5Util.md5(password);//密码加密
        lambdaQueryWrapper.eq(UmsMember::getPassword,password);
        UmsMember umsMember=umsMemberMapper.selectOne(lambdaQueryWrapper);
        log.info("umsMember:{}",umsMember);
        if (umsMember==null){
            return null;
        }
        //生成令牌(令牌的超时时间 令牌的数据)
        LoginUserInfo loginUserInfo=new LoginUserInfo();//存在令牌中的用户信息
        BeanUtils.copyProperties(umsMember,loginUserInfo);
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH,expire);//当前时间+1
        Date date=calendar.getTime();//Calendar转为Date类型型，令牌的过期时间
        return JwtUtil.generateToken(loginUserInfo,date);
    }

    @Override
    public String register(String username, String password,String phone) throws Exception {
        UmsMember umsMember=new UmsMember();
        password=MD5Util.md5(password);
        umsMember.setUsername(username);
        umsMember.setPassword(password);
        umsMember.setMobile(phone);
        umsMemberMapper.insert(umsMember);

        LoginUserInfo loginUserInfo=new LoginUserInfo();
        BeanUtils.copyProperties(umsMember,loginUserInfo);
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH,AuthorityCenterConstant.TOKEN_EXPIRE_TIME);//当前时间+1
        Date date=calendar.getTime();//Calendar转为Date类型型，令牌的过期时间
        return JwtUtil.generateToken(loginUserInfo,date);
    }
}
